import cgi
import logging

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import datastore_types
from google.appengine.api import memcache
import os
from google.appengine.ext.webapp import template

class MainPage(webapp.RequestHandler):
  def get(self):
    items_query = Item.all().order('-date')
    items = items_query.fetch(10)

    template_values = {
      'items': items,
      }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class Edit(webapp.RequestHandler):
  def get(self):
    key = str(self.request.get('key'))
    item = db.get(key)

    template_values = {
      'item': item
      }

    path = os.path.join(os.path.dirname(__file__), 'edit.html')
    self.response.out.write(template.render(path, template_values))


class Put(webapp.RequestHandler):
  def handle(self):
    self.response.headers['Content-Type'] = 'text/plain'

    ui = str(self.request.get('ui'))
    key = str(self.request.get('key'))
    content = self.request.get('content')

    if not content or len(content) == 0:
      if ui:
        self.redirect('/')
      else:      
        self.response.out.write(key)
      return
  
    item = Item()
    try:
      item = db.get(key)
    except datastore_types.datastore_errors.BadKeyError:
      logging.debug("Could not find key %s" % key)
    item.content = self.request.get('content')
    item.put()
    key = str(item.key())
    memcache.set(key, item)

    
    if ui:
      self.redirect('edit?key=%s' % key)
    else:      
      self.response.out.write(key)

  def get(self):
    self.handle()
  def post(self):
    self.handle()

class Get(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/plain'

    key = str(self.request.get('key'))
    item = memcache.get(key)
    if item is None:
      try:
        item = db.get(key)
        memcache.set(key, item)
      except:
        logging.error("Could not find key %s" % key)
    if item is not None:
      self.response.out.write(item.content)
    else:
      self.response.out.write("")


class Item(db.Expando):
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)

application = webapp.WSGIApplication(
                                     [('/', MainPage),
									  ('/edit', Edit),
									  ('/get', Get),
									  ('/put', Put)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()